<template>
  <div class="param-main">
    <div class="breadcrumb" v-if="this.letterBrandVmOb.vehicleOb.id">
      <div v-for="(item, index) in levelList" :key="index">
        <span v-if="index == levelList.length - 1">{{ item.name }}</span>
        <div class="spanClick" v-else>
          <span @click="goBack(item)">{{ item.name }}</span>
          <i
            v-if="index != levelList.length - 1"
            class="el-icon-arrow-right"
            style="padding: 0 2px"
          ></i>
        </div>
      </div>
    </div>
    <el-form
      ref="tblMain"
      :model="serachForm"
      labelPosition="right"
      inline=""
      label-suffix=":"
      label-width="110px"
    >
      <el-row :span="24">
        <el-col :span="8" v-if="!this.letterBrandVmOb.vehicleOb.id">
          <el-form-item label="品牌车系车型">
            <el-cascader
              v-model="brandss"
              :props="props"
              placeholder="名称搜索"
              filterable
              clearable
              @change="getChange"
              :show-all-levels="false"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!this.letterBrandVmOb.vehicleOb.id">
          <el-form-item label="车型名称">
            <el-input
              v-model="serachForm.carName"
              size="small"
              placeholder="车型名称模糊查询"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8" v-if="!this.letterBrandVmOb.vehicleOb.id">
          <el-form-item label="制造商">
            <el-input
              v-model="serachForm.mfrs"
              size="small"
              placeholder=""
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="配件名称">
            <el-input
              v-model="serachForm.name"
              size="small"
              placeholder=""
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="page-pane2">
        <el-button type="primary" size="small" @click="initTableData()"
          >查询</el-button
        >
        <el-button size="small" @click="dataReset()">清空</el-button>
        <!-- <el-button size="small" @click="detailTblMain(1)" type="info" v-if="!this.letterBrandVmOb.vehicleOb.id">新增</el-button> -->
        <!-- <el-button size="small" type="danger" @click="deleteEvent(1)" v-if="!this.letterBrandVmOb.vehicleOb.id"
          >删除</el-button
        > -->
      </div>
    </el-form>
    <div style="height: calc(100% - 160px)">
      <el-table
        ref="tblMain"
        style="margin-top: 10px"
        :data="listData"
        height="100%"
        @selection-change="handleSelectionChange"
        @sort-change="getSortList"
        v-loading.body="loading"
        border
        stripe
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          width="50"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="80px">
          <template slot-scope="scope">
            <!-- <el-button  type="text" @click="detailTblMain(2,scope.row)" v-if="!letterBrandVmOb.vehicleOb.id">编辑</el-button>
            <el-divider direction="vertical" v-if="!letterBrandVmOb.vehicleOb.id"></el-divider>
            <el-button  type="text" @click="deleteEvent(scope.row)" v-if="!letterBrandVmOb.vehicleOb.id">删除</el-button>
            <el-divider direction="vertical" v-if="!letterBrandVmOb.vehicleOb.id"></el-divider> -->
            <el-button type="text" @click="detailTblMain(3, scope.row)"
              >明细</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="图片" align="center">
          <template slot-scope="scope">
            <part-img :key="Math.random()" :path="scope.row.thumbImage"></part-img>
            <!-- <img
              :key="Math.random()"
              :src="thumbImageUrl[scope.row.id.toString()]"
              style="width: 30px; height: 30px"
            /> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="配件名称"
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column prop="matAttrCodeb" label="配件属性" align="center">
          <template slot-scope="scope">
            {{
              formatterFiled(scope.row.matAttrCodeb, 'id', 'name', classifyList)
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="mfrs"
          label="制造商"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="model"
          label="型号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="color"
          label="颜色"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="expiryNum"
          label="保质期天数"
          align="center"
        ></el-table-column>
      </el-table>
    </div>
    <!-- v-show="pageInfo.total != 0" -->
    <el-pagination
      style="margin-top: 10px"
      :current-page.sync="pageInfo.page"
      :page-size="pageInfo.size"
      :total="pageInfo.total"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <add-material
      ref="addMaterial"
      v-if="visible"
      @ok="saveData"
      @cancle="cancle"
      :title="title"
      :row="rowData"
    ></add-material>
  </div>
</template>
<script>
import axios from 'axios'
import COS from 'cos-js-sdk-v5'
import AddMaterial from './addMaterial'
import partImg from './components/partImg.vue'
import {
  addMaterial,
  delMaterial,
  upMaterial,
  getMaterialList,
  getCarLetterList,
  getCarBrandList,
  getCarList,
  getCarClassifyList
} from '@/api/carLine'

export default {
  name: 'applyMain',
  components: {
    AddMaterial,
    partImg
  },
  data() {
    return {
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level, data } = node
          setTimeout(() => {
            if (level == 0) {
              let data = {
                page: 1,
                size: 1000
              }
              getCarLetterList(data).then((res) => {
                const { code = undefined, data = {} } = res.data
                if (!code) {
                  const nodes = data.content.map((item) => ({
                    value: item.id,
                    label: item.name,
                    leaf: false
                  }))
                  resolve(nodes)
                } else {
                  this.$message.error(data)
                }
              })
            } else if (level == 1) {
              let param = {
                page: 1,
                size: 1000,
                letterId: data.value
              }
              getCarBrandList(param)
                .then((res) => {
                  const { code = undefined, data = {} } = res.data
                  if (!code) {
                    // this.brands = data.content;
                    const nodes = data.content.map((item) => ({
                      value: item.id,
                      label: item.name + ' - ' + item.makeName,
                      leaf: false
                    }))
                    resolve(nodes)
                  }
                })
                .catch(() => {
                  this.$message.error('服务器繁忙')
                })
            } else if (level == 2) {
              let param = {
                page: 1,
                size: 1000,
                brandId: data.value
              }
              getCarList(param)
                .then((res) => {
                  const { code = undefined, data = {} } = res.data
                  if (!code) {
                    // this.brands = data.content;
                    const nodes = data.content.map((item) => ({
                      value: item.id,
                      label: item.vehicleModel,
                      leaf: true
                    }))
                    resolve(nodes)
                  }
                })
                .catch(() => {
                  this.$message.error('服务器繁忙')
                })
            } else {
              resolve([])
            }
          }, 1000)
        }
      },
      visible: false,
      rowData: {},
      title: '',
      levelList: [
        {
          name: '所有品牌',
          path: '/product/vehicleModelPart'
        }
      ],
      classifyList: [],
      loading: false,
      listData: [],
      selection: [],
      serachForm: {
        carId: '',
        name: '',
        carName: '',
        // mfrs: '',
        order: ''
      },
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      },
      brands: [],
      brandss: '',
      thumbImageUrl:{}
    }
  },
  created() {
    this.letterBrandVmOb = this.$route.query.data
      ? this.$route.query.data
      : {
          letterOb: {
            id: null,
            name: null,
            path: null
          },
          brandOb: {
            brandId: null,
            name: null,
            path: null
          },
          vehicleOb: {
            id: null,
            vehicleModel: null,
            path: null
          }
        } //品牌对象
    if (this.letterBrandVmOb.vehicleOb.id) {
      let letterOp = {
        letterId: this.letterBrandVmOb.vehicleOb.letterId,
        name: this.letterBrandVmOb.vehicleOb.letterName,
        path: '/product/carSeries'
      }
      this.levelList.push(letterOp)
      let brandOp = {
        brandId: this.letterBrandVmOb.vehicleOb.brandId,
        name: this.letterBrandVmOb.vehicleOb.brandName,
        path: '/product/vehicleModel'
      }
      this.levelList.push(brandOp)
      let vehicleOp = {
        id: this.letterBrandVmOb.vehicleOb.id,
        name: this.letterBrandVmOb.vehicleOb.vehicleModel,
        path: '/product/vehicleModel'
      }
      this.levelList.push(vehicleOp)
      this.brandss = [letterOp.letterId, brandOp.brandId, vehicleOp.id]
      this.serachForm.carId = this.letterBrandVmOb.vehicleOb.id
    }
  },
  mounted() {
    this.getBrandsList().then(() => {
      this.getTopParentList()
      // this.serachForm.brandName = this.levelList[0].name !='所有品牌'? this.levelList[0].name:"";
      this.initTableData()
    })
  },
  methods: {
    /**
     *  排序查询
     */
    getSortList(column) {
      let arr = []
      arr.push(column.prop)
      arr.push(column.order.substring(0, column.order.indexOf('ending')))
      this.serachForm.order = arr.join(',')
      this.initTableData()
    },
    /**
     * 获取码值
     */
    formatterFiled(cellValue, key, val, list) {
      let item = list.find((item) => item[key] === cellValue)
      return item ? item[val] : ''
    },
    /**
     * 获取配件分类的树形数据
     */
    getTopParentList() {
      let param = {
        page: 1,
        size: 1000
      }
      getCarClassifyList(param)
        .then((res) => {
          const { code = undefined, data = {} } = res.data
          if (!code) {
            this.classifyList = data.content
          } else {
            this.$message.error('获取配件分类失败')
          }
        })
        .catch(() => {
          this.$message.error('服务器繁忙')
        })
    },
    goBack(item) {
      if (item.name != '所有品牌') {
        let datas = {
          letterOb: this.letterBrandVmOb.letterOb,
          brandOb: this.letterBrandVmOb.brandOb,
          vehicleOb: this.letterBrandVmOb.vehicleOb
        } //品牌对象
        this.$router.push({
          path: item.path,
          query: {
            data: datas
          }
        })
      } else {
        let data = {
          letterOb: this.letterBrandVmOb.letterOb.id
            ? this.letterBrandVmOb.letterOb
            : { name: '全部', id: '' },
          brandOb: this.letterBrandVmOb.brandOb,
          vehicleOb: this.letterBrandVmOb.vehicleOb
        }
        this.$router.push({
          path: item.path,
          query: {
            data: data
          }
        })
      }
    },
    /**
     * 获取品牌级联数据
     */
    getChange(val) {
      this.serachForm.carId = val[val.length - 1]
    },
    /**
     * 获取品牌列表信息
     */
    getBrandsList() {
      return new Promise((resolve) => {
        let data = {
          page: 1,
          size: 1000
        }
        getCarLetterList(data).then((res) => {
          const { code = undefined, data = {} } = res.data
          if (!code) {
            this.brands = data.content
            resolve(this.brands)
          } else {
            this.$message.error(data)
          }
        })
      })
    },
    /**
     * 获取车系信息
     */
    getCarBrandList(letterId) {
      let param = {
        page: 1,
        size: 1000,
        letterId
      }
      return new Promise((resolve) => {
        getCarBrandList(param)
          .then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              // this.brands = data.content;
              resolve(data.content)
            }
          })
          .catch(() => {
            this.$message.error('服务器繁忙')
          })
      })
    },
    /**
     * 获取车型信息
     */
    getCarList(letterId) {
      let param = {
        page: 1,
        size: 1000,
        letterId
      }
      return new Promise((resolve) => {
        getCarList(param)
          .then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              // this.brands = data.content;
              resolve(data.content)
            }
          })
          .catch(() => {
            this.$message.error('服务器繁忙')
          })
      })
    },
    /**
     * 点击功能按钮
     */
    detailTblMain(type, row) {
      if (type != 1) {
        this.title = type == 2 ? '修改配件' : '配件详情'
        this.rowData = JSON.parse(JSON.stringify(row))
      } else {
        this.title = '新增配件'
        this.rowData = {}
      }
      this.visible = true
    },
    /**
     * 保存数据
     */
    saveData(val) {
      if (this.title == '新增配件') {
        addMaterial(val).then((res) => {
          const { code = undefined, data = {} } = res.data
          if (!code) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.initTableData()
            this.cancle()
          } else {
            this.$message({
              type: 'error',
              message: '操作失败!'
            })
          }
        })
      } else {
        upMaterial(val).then((res) => {
          const { code = undefined, data = {} } = res.data
          if (!code) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.initTableData()
            this.cancle()
          } else {
            this.$message({
              type: 'error',
              message: '操作失败!'
            })
          }
        })
      }
    },
    /**
     * 关闭弹框
     */
    cancle() {
      this.visible = false
    },
    /**
     * 多选
     */
    handleSelectionChange(val) {
      this.selection = val
    },
    /**
     * 重置
     */
    dataReset() {
      if (this.letterBrandVmOb.vehicleOb.id) {
        this.serachForm.name = ''
      } else {
        this.brandss = ''
        this.serachForm.name = ''
        this.serachForm.carId = ''
        // this.serachForm.mfrs = ''
        this.serachForm.carName = ''
      }
      this.pageInfo.page = 1
      this.pageInfo.size = 10
      this.serachForm.order = ''
      this.initTableData()
    },
    /**
     * 分页
     */
    handleSizeChange(val) {
      this.pageInfo.size = val
      this.initTableData()
    },
    /**
     * 分页
     */
    handleCurrentChange(val) {
      this.pageInfo.page = val
      this.initTableData()
    },
    /**
     * 获取配件数据列表
     */
    initTableData() {
      let me = this
      me.selection = []
      let param = {
        page: me.pageInfo.page,
        size: me.pageInfo.size,
        ...me.serachForm
      }
      me.loading = true
      getMaterialList(param)
        .then((res) => {
          me.loading = false
          const { code = undefined, data = {} } = res.data
          if (!code) {
            me.listData = data.content;
            // me.getImgUrl(data.content)
            me.pageInfo.total = data.totalElements
          } else {
            me.$message.error(data)
          }
        })
        .catch(() => {
          me.$message.error('服务器繁忙')
          me.loading = false
        })
    },
    /**
     * 删除
     */
    deleteEvent(row) {
      let ids = []
      if (row == '1') {
        if (this.selection.length < 1) {
          this.$message.warning('请至少选择一条数据')
          return
        }
        ids = this.selection.map((item) => {
          return item.id
        })
      } else {
        ids.push(row.id)
      }
      this.$confirm('此操作将永久删除该配件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delMaterial(ids).then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.initTableData()
            } else {
              this.$message({
                type: 'error',
                message: '操作失败!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
      /**
     * 获取图片地址
     */
    getImgUrl(list) {
      let that = this;
      that.thumbImageUrl = {}
      var cos = new COS({
          getAuthorization: function (options, callback) {
            // 初始化时不会调用，只有调用 cos 方法（例如 cos.putObject）时才会进入
            // 异步获取临时密钥
            axios
              .get(
                'http://101.43.187.89:30001/cos-authorization/getAuthorization',
                {
                  params: {
                    prefix: 'images',
                    type: 'getObject',
                    bucketName: 'file-1322379458'
                  }
                }
              )
              .then((res) => {
                if (res.data.code == 0) {
                  var data = res.data.data
                  console.log('数据：', data)
                  callback({
                    TmpSecretId: data.tmpSecretId,
                    TmpSecretKey: data.tmpSecretKey,
                    SecurityToken: data.sessionToken,
                    // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                    StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                    ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000000              // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
                  })
                }
              })
          }
        })
        list.forEach(item=>{
          if(item.thumbImage){
            console.log(item.thumbImage);
            cos.getObjectUrl(
              {
                Bucket: 'file-1322379458' /* 填入您自己的存储桶，必须字段 */,
                Region: 'ap-chengdu' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
                Key: item.thumbImage /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
                Sign: true,
                onProgress: function (progressData) {
                  console.log(JSON.stringify(progressData))
                },
              },
              function (err, data) {
                console.log(typeof(item.id));
                let id = item.id.toString()
                that.thumbImageUrl[id] = data.Url;
                console.log(that.thumbImageUrl[id]);
                  console.log(that.thumbImageUrl);
              }
            )
          }else{
              let id = item.id.toString()
            that.thumbImageUrl[id] = "";
          }
        })
    },
  }
}
</script>
<style lang="less" scoped>
.breadcrumb {
  display: flex;
  padding: 0 0 9px 9px;
  .spanClick {
    cursor: pointer;
    color: #409eff;
  }
}
</style>
